(function($){
	//初始化参数
    var defaultParams = {
        activityid : null,//活动ID
        picMap : {},//存储上传的图片对象
        current_viewid : null,//当前编辑的视图ID
        current_info : null,//编辑按钮的对象info值
        current_obj : null,//编辑按钮的对象
        imgUrl : null,//图片地址
        type : null,//编辑的视图类型
        sessionId : null,
        //显示的按钮ID
        buttons_type : {}//需要显示的工具按钮类型
    };
	//浮动层的隐藏和显示
	var floatMethod = {
		edit : function(){
			$("#parent").show();
		},
		scan : function(){
			$("#parent").show();
			$("#selectTools").hide();
			$("#selectItemSave").hide();
		}
	};

    $.activity = {
        //初始化参数
        init : function(options){
            var options = $.extend(defaultParams,options);
            displayFloat();
        }
    };

    $.fn.extend({
        //效果预览
        scanView : function(){
            return this.each(function(){
            	var resolutionValue=$('input[name="resolution"]:checked').val();
            	showAlert($(this),null);
            	if(resolutionValue=='hd'){
					showHdBackground();
				}else{
					showBackground();
				}
            	floatMethod.scan();
            });
        },
        //显示弹出框
		alertPic : function(sign){
			var resolutionValue=$('input[name="resolution"]:checked').val();
			var str = defaultParams.buttons_type[sign];
			if(str == null || str == "")
				if(sign!="flashPic"){
					str = defaultParams.buttons_type["other"];
				}
			return this.each(function(){
				showAlert($(this),str);
				if(defaultParams.type != "background"){
					if(resolutionValue=='hd'){
						showHdBackground();
					}else{
						showBackground();
					}
				}
				displayButton(str);
				floatMethod.edit();
				//修改弹出框标题
				$("#selectItemContentTitle").html($(this).parent().prev().html());
			});
		},
		//图片上传 
		uploadPic : function(){
			return this.each(function(){
				var objId = $(this).attr("id");
				$(this).uploadify({
					'swf'           :'../../swf/uploadify.swf',
					'uploader'      :'../activityUploadPictures.do;jsessionid='+defaultParams.sessionId,//跳转页面,传session否则flash插件会被拦截
					'fileObjName'   :'uploadify',
					'cancelImg' 	:"imgs/uploadify-cancel.png",
					'queueId'		:"fileQueue",
					'fileTypeExts'	:"*.jpg;*.gif;*.png",//限制文件类型
					'auto'			:true,//是否自动上传
					'multi'			:false,//是否允许多文件上传
					'buttonText'	:"图片上传",
					'formData':{'picType':'活动'},
					'method'		:"POST",
					'onUploadSuccess' : function(file,data,response) {//上传完成时触发 每个文件触发
						if(response == false){
							$("#message").text("图片上传失败！");
							return false;
						}else{//图片上传成功，图片对象赋值
							setImgData(objId,data);
						}
					}
				});
				
			});
		},
		//显示按钮坐标设置界面
		displayPic : function(id,sign){
			return this.each(function(){
				var fileId = $(this).siblings("div.uploadify").attr("id");
				var num = (fileId==null?0:fileId.substring(4));
				var pathobj = getImgData(fileId);
				var obj = $.parseJSON(pathobj);
				if(num == 1)id=defaultParams.type;
				if(sign == "show"){
					//setPositionValue(num,id);
					if(obj != null){
						createPicObject({"id":id,"left":"300","top":"45","width":obj.width,"height":obj.height,"imgpath":defaultParams.imgUrl+obj.imgpath,"num":num});
					}else{
						getViewObject({"id":id,"num":num,"activityid":defaultParams.activityid});//f_aoa_activityid
					}
				}else if(sign == "hidden"){
					//删除坐标不上传
					//$('.coordinate > input[name="sign'+num+'"]').parent().remove();
					$("#"+id).remove();
				}
			});
		}
    });
    //获取指定按钮的视图对象
	function getViewObject(obj){
		var num = obj.num;
		var sign = (num==1?"view":"button");
		var viewid = defaultParams.current_viewid;
		var json = '{"sign":"'+sign+'","viewid":"'+viewid+'","activityid":"'+obj.activityid+'","type":"'+defaultParams.type+'","info":"'+obj.id+'"}';
		$.post("../select_activityViewInfo.do",{"json":json},function(data){
			if(data != null){
				//一开始出现在坐标原点
				createPicObject({"id":obj.id,"left":300+parseInt(data.x),"top":45+parseInt(data.y),"width":data.width,"height":data.height,"imgpath":defaultParams.imgUrl+data.picpath,"num":num});
			}else{
				//一开始出现在坐标原点
				createPicObject({"id":obj.id,"left":"300","top":"45","width":"150","height":"30","imgpath":"","num":num});
			}
			//$("#"+obj.id).show();//放在这里是为了ajax加载完后再显示图片
		},"json");
	}
    //创建图片对象，控制拖拽和大小
    function createPicObject(obj){
		var width = (obj.width>=1280?1280:obj.width);
		var height = (obj.height>=720?720:obj.height);
		if($("#"+obj.id).length > 0){//已存在视图对象
			$("#"+obj.id+">img").attr("src",obj.imgpath);//先换好图片，然后再定坐标
			$("#"+obj.id).css({"left":obj.left+"px","top":obj.top+"px","width":width+"px","height":height+"px"});
		}else{//不存在就生成
			var str = "";
			str += '<div id="'+obj.id+'" class="drag" style="position:absolute;left:'+obj.left+'px;top:'+obj.top+'px;width:'+width+'px;height:'+height+'px;">';
			str += '<img src="'+obj.imgpath+'" width="100%" height="100%"/>';
			str += '<div class="resizeL"></div>';
			str += '<div class="resizeT"></div>';
			str += '<div class="resizeR"></div>';
			str += '<div class="resizeB"></div>';
			str += '<div class="resizeLT"></div>';
			str += '<div class="resizeTR"></div>';
			str += '<div class="resizeBR"></div>';
			str += '<div class="resizeLB"></div>';
			str += '</div>';
			if(obj.num == 1)
				$("#selectContent").after(str);
			else
				$("#parent").append(str);
		}
		$("#"+obj.id).show();//显示背景图
		change(document.getElementById(obj.id),obj.num);
	}
	//弹出编辑浮动层窗口，编辑坐标
    function showAlert(obj,str){
    	var _this = obj;
    	defaultParams.current_obj = _this;
		var info = _this.attr("id");
		var viewid = _this.siblings('input[name="viewid"]').val();
		defaultParams.current_info = info;
		var json = '{"sign":"all","activityid":"'+defaultParams.activityid+'"';
		if(viewid != null && viewid.length > 0){
            json += ',"viewid":"'+viewid+'"';
        }else{
            json += ',"type":"'+defaultParams.type+'","info":"'+info+'"';
        }
        if(str != null && str.length > 0){
        	json += ',"button_types":"'+str+'"';
        }
        json += "}";
        //清空所有按钮视图
		$(".drag").each(function(){
			$(this).remove();
		});
		$.post("../select_activityViewInfo.do",{"json":json},function(data){
			viewid = (data != null ? data.viewid : "0");
			_this.siblings('input[name="viewid"]').val(viewid);//查出对应的viewid
			//$("#current_viewid").val(viewid);
			defaultParams.current_viewid = viewid;
			if(data != null){
                createPicObject({"id":defaultParams.type,"left":300+parseInt(data.x),"top":45+parseInt(data.y),
                    "width":data.width,"height":data.height,"imgpath":defaultParams.imgUrl+data.picpath,"num":"1"});
                $("#flashtime").val(data.flashtime);
                //setPositionValue(1,defaultParams.type);//生成背景坐标
                var buttons = data.buttons;
                if(buttons != null && buttons.length > 0){//显示按钮
                	var num = 0;
                    for(var i=0;i<buttons.length;i++){
						var filePicId = $('div.selectSub>img[type="'+buttons[i].f_avb_type+'"]').siblings("div.uploadify").attr("id");
						if(filePicId != null){
							num = filePicId.substring(4);
						}
                        createPicObject({"id":buttons[i].f_avb_type,"left":300+parseInt(buttons[i].f_avb_x),"top":45+parseInt(buttons[i].f_avb_y),
                            "width":buttons[i].f_avb_width,"height":buttons[i].f_avb_height,"imgpath":defaultParams.imgUrl+buttons[i].f_avb_focus,"num":num});
                    }
                }
            }
		},"json");
	}
    //显示背景图片作为参考
    function showBackground(){
		var json = '{"sign":"all","activityid":"'+defaultParams.activityid+'","type":"background","info":"index"}';
		$.post("../select_activityViewInfo.do",{"json":json},function(data){
			if(data != null){
				var str = '<div style="position:absolute;left:300px;top:45px;width:640px;height:530px;display:block;z-index:10;border:2px solid red;border-radius:5px;" id="backgroundPic"><img width="100%" height="100%" src="'+defaultParams.imgUrl+data.picpath+'"></div>';
				$("#backgroundHdPic").attr("style","display:none;");
				$("#selectContent").after(str);
            }
		},"json");
	}  
    
    //显示高清背景图片作为参考
    function showHdBackground(){
		var json = '{"sign":"all","activityid":"'+defaultParams.activityid+'","type":"background","info":"index"}';
		$.post("../select_activityViewInfo.do",{"json":json},function(data){
			if(data != null){
				var str = '<div style="position:absolute;left:300px;top:45px;width:1280px;height:720px;display:block;z-index:10;border:2px solid red;border-radius:5px;" id="backgroundHdPic"><img width="100%" height="100%" src="'+defaultParams.imgUrl+data.picpath+'"></div>';
				$("#backgroundPic").attr("style","display:none;");
				$("#selectContent").after(str);
            }
		},"json");
	}
	//显示对应的按钮
	function displayButton(ids){
		$(".selectSub").remove();//移除所有工具按钮
		$(".selectSubFlash").remove();//移除动画图片时间文本框
		//显示设置背景工具按钮
		var str = "";
		str += '<div class="selectSub">';
    	str += '<div class="btn">背景：</div>';
        str += '<input type="file" id="file1" class="filePic"/>';
    	str += '<img title="删除图片" src="imgs/delete_activity.png" class="deletePic" type="'+defaultParams.current_info+'"/>';
        str += '<img title="添加图片" src="imgs/add_activity.png" class="addPic" type="'+defaultParams.current_info+'"/>';
    	str += '</div>';
    	if(defaultParams.current_info=="flashPic"){
       	 	str += '<div class="selectSubFlash"><span style="color:black;" >动画图片时间: </span><input type="text" style="width:50px;" id="flashtime" /><span style="color:red;" >单位：秒</span></div>';
        }
        $("#selectItemCount").append(str);
        $("#file1").uploadPic(defaultParams.sessionId);
        str = "";
		$.post("../select_buttonUrl.do",{"json":ids},function(data){
			//获取其他需要设置的工具按钮
			if(data != null && data.length > 0){//显示按钮
	            for(var i=0;i<data.length;i++){
					str += '<div class="selectSub">';
	            	str += '<div class="btn">'+data[i].f_abu_info+'：</div>';
	                str += '<input type="file" id="file'+(i+2)+'" class="filePic"/>';
	            	str += '<img title="删除图片" src="imgs/delete_activity.png" class="deletePic" type="'+data[i].f_avb_type+'" />';
	                str += '<img title="添加图片" src="imgs/add_activity.png" class="addPic" type="'+data[i].f_avb_type+'" />';
	            	str += '</div>';
	                $("#selectItemCount").append(str);
	                $("#file"+(i+2)).uploadPic();
	                str = "";
	            }
	        }
		},"json");
		$("img.deletePic").live("click",function(){
			$(this).displayPic($(this).attr("type"),"hidden");
		});
		$("img.addPic").live("click",function(){
			$(this).displayPic($(this).attr("type"),"show");
		});
	}
	//设置浮动层
	function displayFloat(){
		//工具栏
		var str = '<div id="selectTools" style="height:1500px;">';
        str += '<div id="selectItemAd" class="selectItemtit bgc_ccc">';
        str += '<h2 id="selectItemToolTitle" class="selectItemleft">工具栏</h2>';
        str += '</div>';
        str += '<div id="selectItemCount" class="selectItemcount"></div>';
		str += '</div>';
		//视图栏
		str += '<div id="selectContent">';
        str += '<div id="selectItemAd" class="selectItemtit bgc_ccc">';
        str += '<h2 id="selectItemContentTitle" class="selectItemleft">活动页面</h2>';
        str += '<div id="selectItemClose" class="selectItemright">关闭</div>';
        str += '<div id="selectItemSave" class="selectItemright">保存</div>';
        str += '</div></div>';
		$('#parent').append(str);
        $("#selectItemClose").live('click',function() {//新生成的DOM需用live
			$("div.drag").remove();
			$("#backgroundPic").remove();
			$("#backgroundHdPic").remove();
			$("#parent").hide();
//			$(".coordinate").remove();
			$("#selectTools").show();
			$("#selectItemSave").show();
		});
		$("#selectItemSave").live("click",function(){
			submitView();
		});
	}
	function selectItemClose(){
		$("div.drag").remove();
		$("#backgroundPic").remove();
		$("#backgroundHdPic").remove();
		$("#parent").hide();
//		$(".coordinate").remove();
		$("#selectTools").show();
		$("#selectItemSave").show();
	}
	//拼接坐标json字符串
	function setPositionStr(){
		var jsondata = "[";
		$(".drag").each(function(index,element){
		   /*var x = $(this).offset().left-300;
		   var y = $(this).offset().top-45;
		   var w = $(this).width();
		   var h = $(this).height();*/
		   
		   var x = Math.ceil($(this).offset().left-300);
		   var y = Math.ceil($(this).offset().top-45);
		   var w = Math.ceil($(this).width());
		   var h = Math.ceil($(this).height());
		   x = x<0 ? 0 : x;
		   y = y<0 ? 0 : y;
		   
		   var type = $(this).attr("id");
		   var picpath = $(this).children("img").attr("src");
		   
		   if(picpath.indexOf("undefined")>=0)
		   		picpath= "";
		   else
		   		picpath = picpath.substring(picpath.indexOf("PIC/imgs/"));
		   
		   if(type == "background" || type == "alert" || type == "order"){
			   jsondata += '{"sign":"view","info":"'+defaultParams.current_info+'",';
			   if(defaultParams.current_info=="flashPic"){
				   var flashtime = $("#flashtime").val();
				   jsondata += '"flashtime":"'+flashtime+'",';
			   }
		   }else{
			   if(jsondata.indexOf("}") != -1){
				   jsondata += ",";
			   }
			   jsondata += '{"sign":"button",';
		   }
		   jsondata += '"x":"'+x+'","y":"'+y+'","w":"'+w+'","h":"'+h+'","type":"'+type+'","picpath":"'+picpath+'"}';
		});
		jsondata += "]";
		return jsondata;
	}
	//保存视图坐标设置
	function submitView(){
		var jsondata = "{";
		jsondata += '"f_aoa_activityid":"'+defaultParams.activityid+'","current_viewid":"'+defaultParams.current_viewid+'"';
		var viewstr = setPositionStr();
		jsondata += ',view:'+viewstr;
		jsondata += "}";
		$.post("../activityViewUpdate.do",{"json":jsondata,"stime":stime,"sign":sign},function(data){
			defaultParams.current_obj.siblings('input[name="viewid"]').val(data);//保存添加后viewid
			defaultParams.current_viewid = data;
			alert("保存成功！");
			defaultParams.current_obj.siblings('span[name="msg"]').text("视图编辑成功");
			//$("#message").text("视图保存成功");
			if($("#saveBtn")){
				$("#saveBtn").click();
			}
			window.location.reload();
			//selectItemClose();
		});
	}
	//获取上传图片对象
	function getImgData(id){
		return defaultParams.picMap[id];
	}
	//存入上传图片对象
	function setImgData(objId,data){
		defaultParams.picMap[objId] = data;
	}

})(jQuery);